package com.gxc.aspect;

import com.alibaba.fastjson.JSONObject;
import com.gxc.utils.NowDate;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * AOP.
 *
 * @author 宫新程
 * @since 2018/12/14 12:56 PM
 */
@Slf4j
@Aspect
@Configuration
public class MyAspect {

  /** 注解式 切入点. */
  @Pointcut("@annotation(com.gxc.annotation.MyLogAnnotation)")
  public void myAnnotationPointCut() {}

  @Pointcut("@annotation(org.springframework.stereotype.Controller)")
  public void myAnnotationPointCut2() {}

  /** 环绕通知. */
  @Around("myAnnotationPointCut() || myAnnotationPointCut2()")
  public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    log.info("环绕通知执行前：{}", NowDate.getNowDate());
    Object proceed = proceedingJoinPoint.proceed();
    log.info("环绕通知执行后：{}", NowDate.getNowDate());
    return proceed;
  }

  /** 环绕通知. */
  @Pointcut("execution(* com.gxc.controller.*Controller.*(..))")
  public void myControllerPointCut() {}

  //@Around("myControllerPointCut()")
  public Object around2(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    ServletRequestAttributes requestAttributes =
        (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = requestAttributes.getRequest();


    /** 获取request中的所有key. */
    Enumeration<String> parameterNames = request.getParameterNames();
    while (parameterNames != null && parameterNames.hasMoreElements()) {
      String key = parameterNames.nextElement();
      System.out.println(key + " ==== " + request.getParameter(key));
    }

    Map<String, String[]> parameterMap = request.getParameterMap();
    log.info("请求入参：" + JSONObject.toJSONString(parameterMap));
    String url = request.getRequestURL().toString();
    log.info("请求URL：" + url);
    String method = request.getMethod();
    log.info("请求method：" + method);
    String remoteAddr = request.getRemoteAddr();
    log.info("请求IP：" + remoteAddr);
    long start = System.currentTimeMillis();
    Object proceed = proceedingJoinPoint.proceed();
    long end = System.currentTimeMillis();
    log.info("请求时长：" + (end - start) + "ms");

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames != null && headerNames.hasMoreElements()) {
      String key = headerNames.nextElement();
      System.out.println(key + " ==== " + request.getHeader(key));
    }
    return proceed;
  }
}
